import React, { useEffect, useState } from "react";
import { Button, Table, message, Popconfirm } from "antd";
import {
  listSuppliers,
  createSupplier,
  updateSupplier,
  deleteSupplier,
  listWarehouses,
  createWarehouseRecord,
  updateWarehouseRecord,
  updateWarehouse,
  createWarehouse,
  deleteWarehouse,
} from "../../api/ckgl";
import ListWarehousesModal from "./componets/ListWarehousesModal";
// import RemindTag from "../../components/RemindTag";

const ListWarehouses = () => {
  const [supplierList, setSupplierList] = useState<any[]>([]);
  const [totalSuppliers, setTotalSuppliers] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [isSupplierModalVisible, setIsSupplierModalVisible] = useState(false);
  const [currentSupplier, setCurrentSupplier] = useState<any>(null);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "仓库名称",
      dataIndex: "warehouse_name",
      key: "warehouse_name",
      render: (text: string) => <span>{text}</span>,
    },
    // {
    //   title: "库存",
    //   dataIndex: "inventory",
    //   key: "inventory",
    // },
    // {
    //   title: "是否提醒",
    //   dataIndex: "remind",
    //   key: "remind",
    //   render: (_: any, record: any) => <RemindTag remind={record.remind} />,
    // },
    // {
    //   title: "提醒阈值",
    //   dataIndex: "reminder_threshold",
    //   key: "reminder_threshold",
    // },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      render: (_: any, record: any) => (
        <>
          <Button type="link" onClick={() => handleEditSupplier(record)}>
            编辑
          </Button>
          <Popconfirm
            okText="确定"
            cancelText="取消"
            title="确定删除"
            onConfirm={() => handleDeleteSupplier(record)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  const handleDeleteSupplier = (record: any) => {
    deleteWarehouse({
      warehouse_id: record.id,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      message.success(`"${record.warehouse_name}" 删除成功`);
      // 更新当前页
      reset(currentPage);
    });
  };

  const handleEditSupplier = (record: any) => {
    setCurrentSupplier(record);
    setIsSupplierModalVisible(true);
  };

  const getListSuppliers = (page: number) => {
    // 调用 listSuppliers API，并处理响应
    listWarehouses({
      page,
      size: pageSize,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { warehouses, total } = res.data;
      setSupplierList(warehouses);
      setTotalSuppliers(total);
    });
  };

  const reset = (page: number) => {
    getListSuppliers(page);
  };

  const handleSupplierModalOk = async (values: any) => {
    // 根据情况调用 createSupplier 或 updateSupplier API，并处理响应
    if (currentSupplier) {
      // 更新
      let msg = "更新成功";
      await updateWarehouse({
        warehouse_id: currentSupplier?.id,
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    } else {
      // 添加
      let msg = "添加成功";
      await createWarehouse({
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    }
    reset(currentPage);
    setIsSupplierModalVisible(false);
  };

  useEffect(() => {
    getListSuppliers(currentPage);
  }, [currentPage]);

  return (
    <div>
      <Button
        style={{ marginTop: "7px", marginLeft: "10px", float: "right" }}
        onClick={() => {
          setIsSupplierModalVisible(true);
          setCurrentSupplier(null);
        }}
        size="large"
        type="primary"
      >
        添加仓库
      </Button>
      <Table
        dataSource={supplierList}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalSuppliers,
        }}
      />
      <ListWarehousesModal
        title={currentSupplier ? "编辑仓库" : "添加仓库"}
        visible={isSupplierModalVisible}
        onCancel={() => setIsSupplierModalVisible(false)}
        onOk={handleSupplierModalOk}
        defaultValue={currentSupplier || {}}
      />
    </div>
  );
};

export default ListWarehouses;
